<template>
  <div>
    <CustomTable
      ref="customTableRef"
      url="/file/search/batch/list"
      :searchInfo="searchInfo"
      methods="post"
      :loading="true"
      :columns="columns"
    >
      <template #searchPre>
        <el-space>
          <el-button
            type="primary"
            size="small"
            @click="handleFileBatchClean(data, 1, false)"
          >
            点呼导出清零
          </el-button>

          <el-button
            type="primary"
            size="small"
            style="margin-left: 0"
            @click="handleFileBatchClean(data, 2, false)"
          >
            群呼导出清零
          </el-button>

          <el-button
            type="primary"
            size="small"
            style="margin-left: 0"
            @click="handleFileBatchClean(data, 3, false)"
          >
            AI导出清零
          </el-button>
        </el-space>
      </template>
      <template #status="{ data }">
        <el-tag :type="data.status === 1 ? '' : 'danger'">
          <span>导入{{ data.status === 1 ? '成功' : '失败' }}</span>
        </el-tag>
      </template>
      <template #synBlackStatus="{ data }">
        <el-tag :type="synMap[data.synBlackStatus || 0].type">
          <span>{{ synMap[data.synBlackStatus || 0].label }}</span>
        </el-tag>
      </template>
      <template #synIcInfoStatus="{ data }">
        <el-tag :type="synMap[data.synIcInfoStatus || 0].type">
          <span>{{ synMap[data.synIcInfoStatus || 0].label }}</span>
        </el-tag>
      </template>
      <template #option="{ data }">
        <el-button
          link
          type="primary"
          size="small"
          @click="handleDistinctByBatch(data)"
        >
          批次内去重
        </el-button>
        <el-button
          link
          type="primary"
          size="small"
          @click="handleSynchronousInfo(data)"
        >
          同步开票纳税信息
        </el-button>
        <el-button
          link
          type="primary"
          size="small"
          @click="handleCheckInfo(data)"
        >
          三要素校验
        </el-button>

        <el-button
          link
          type="primary"
          size="small"
          @click="handleDistinct(data, 2)"
        >
          全库去重保留最新
        </el-button>
        <el-button
          link
          type="primary"
          size="small"
          @click="handleDistinct(data, 1)"
        >
          全库去重保留最早
        </el-button>

        <el-button
          link
          type="primary"
          size="small"
          @click="handleAsync(data, 1)"
        >
          同步工商信息
        </el-button>
        <!-- <el-button
          link
          type="primary"
          size="small"
          @click="handleAsync(data, 2)"
          >同步风险等级
        </el-button> -->
        <el-button link type="primary" size="small" @click="handleDelete(data)">
          删除
        </el-button>

        <el-popover placement="bottom" trigger="hover">
          <template #reference>
            <el-button link type="primary" size="small">
              清零
              <el-icon class="el-icon--right">
                <DArrowRight />
              </el-icon>
            </el-button>
          </template>
          <div>
            <el-button
              link
              type="primary"
              size="small"
              @click="handleFileBatchClean(data, 1, true)"
            >
              点呼导出清零
            </el-button>
          </div>
          <div>
            <el-button
              link
              type="primary"
              size="small"
              style="margin-left: 0"
              @click="handleFileBatchClean(data, 2, true)"
            >
              群呼导出清零
            </el-button>
          </div>
          <div>
            <el-button
              link
              type="primary"
              size="small"
              style="margin-left: 0"
              @click="handleFileBatchClean(data, 3, true)"
            >
              AI导出清零
            </el-button>
          </div>
        </el-popover>

        <el-popover placement="bottom" trigger="hover">
          <template #reference>
            <el-button link type="primary" size="small">
              结束同步
              <el-icon class="el-icon--right">
                <DArrowRight />
              </el-icon>
            </el-button>
          </template>
          <div>
            <el-button
              link
              type="primary"
              size="small"
              @click="handleFileBatchStopSyn(data)"
            >
              结束工商信息同步
            </el-button>
          </div>
          <!-- <div>
            <el-button
              link
              type="primary"
              size="small"
              @click="handleFileBatchStopSynBlack(data)"
              >结束风险等级同步
            </el-button>
          </div> -->
        </el-popover>
      </template>
    </CustomTable>
  </div>
</template>
<script setup name="BatchNameFile">
import {
  getBatchBlack,
  getBatchDelete,
  getBatchUpdate,
  getJobStatus,
  postFileBatchClean,
  postFileBatchStopSyn,
  postFileBatchStopSynBlack,
} from '@/api/uploadFile.js'
import request from '@/utils/request'

import { DArrowRight } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { provide, reactive, ref } from 'vue'

const customTableRef = ref()
const searchInfo = ref([
  { key: 'batchName', label: '批次名' },
  {
    key: 'queryDate',
    label: '查询周期',
    type: 'dateRange',
    keys: ['createTimeStart', 'createTimeEnd'],
  },
])

const synMap = [
  { type: 'info', label: '未同步' },
  { type: 'warning', label: '同步中' },
  { type: 'success', label: '同步完成' },
  { type: 'danger', label: '同步暂停' },
]

const columns = ref([
  {
    prop: 'batchName',
    minWidth: 200,
    label: '批次名',
    fixed: 'left',
  },
  {
    prop: 'createTime',
    minWidth: 160,
    label: '创建时间',
  },
  {
    prop: 'importNum',
    minWidth: 100,
    label: '导入记录数',
  },
  {
    prop: 'excelNum',
    label: '源文件记录数',
  },
  {
    // 0未同步；1同步中；2同步完成；3同步暂停
    prop: 'synIcInfoStatus',
    label: '工商信息同步状态',
  },
  {
    // 0未同步；1同步中；2同步完成；3同步暂停
    prop: 'distinctNum',
    label: '重复率',
  },
  {
    prop: 'option',
    width: 700,
    fixed: 'right',
    label: '操作',
  },
])

const updateSuccess = (e) => {
  console.log(e)
}
const handleView = (data) => {
  state.visible = true
  state.id = data.id
  state.data = data
}
const state = reactive({
  visible: false,
  id: null,
})

// 去重
const handleDistinct = ({ batchName }, distinctType) => {
  request
    .post('/file/search/batch-distinct', { batchName, distinctType })
    .then((res) => {
      if (res.code === 200) {
        ElMessage.success('去重成功！')
      } else {
        ElMessage.error(res.msg)
      }
    })
}

// 批次去重
const handleDistinctByBatch = ({ batchName }) => {
  request
    .post('/file/search/batch-distinct-byBatch', { batchName })
    .then((res) => {
      if (res.code === 200) {
        ElMessage.success('批次去重成功！')
      } else {
        ElMessage.error(res.msg)
      }
    })
}

// 三要素校验
const handleCheckInfo = ({ batchName }) => {
  request.post('/file/search/check-info', { batchName }).then((res) => {
    if (res.code === 200) {
      ElMessage.success('三要素校验成功！')
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 同步开票纳税信息
const handleSynchronousInfo = ({ batchName }) => {
  request.post('/file/search/ns-kp-info', { batchName }).then((res) => {
    if (res.code === 200) {
      ElMessage.success('同步开票纳税信息成功！')
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 同步工商信息
const handleAsync = (data, type) => {
  ElMessageBox.confirm(
    `${type === 1 ? '确定同步工商信息' : '确定同步风险等级'}？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const res = await getJobStatus()
      if (res.msg === 'true') {
        ElMessage.error('当前有正在进行中的任务，请稍后再试')
        return
      }

      if (type === 1) {
        getBatchUpdate({
          batchName: data.batchName,
        }).then((res) => {
          if (res.code === 200) {
            ElMessage.success('同步工商信息成功')
            customTableRef.value.fetchData()
          }
        })
      } else {
        getBatchBlack({
          batchName: data.batchName,
        }).then((res) => {
          if (res.code === 200) {
            ElMessage.success('同步风险等级成功')
            customTableRef.value.fetchData()
          }
        })
      }
    })
    .catch(() => {})
}

// 删除
const handleDelete = (data) => {
  ElMessageBox.confirm(`确定删除选择的数据么？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const res = await getJobStatus()
      if (res.msg === 'true') {
        ElMessage.error('当前有正在进行中的任务，请稍后再试')
        return
      }

      getBatchDelete({
        batchName: data.batchName,
      }).then((res) => {
        if (res?.code === 200) {
          ElMessage.success('删除成功')
          customTableRef.value.fetchData()
        } else {
          ElMessage.error('删除失败')
        }
      })
    })
    .catch(() => {})
}

const handleFileBatchClean = async (data, type, isBatchName) => {
  const res = await getJobStatus()
  if (res.msg === 'true') {
    ElMessage.error('当前有正在进行中的任务，请稍后再试')
    return
  }

  ElMessageBox.confirm(
    ` 确定要进行${
      type == 1
        ? '点呼导出清零'
        : type == 2
        ? '群呼导出清零'
        : type == 3
        ? 'AI导出清零'
        : ''
    }的操作么`,
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      postFileBatchClean({
        batchName: isBatchName ? data.batchName : null,
        cleanType: type,
      }).then(() => {
        ElMessage.success('清零成功')
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消成功',
      })
    })
}

const handleFileBatchStopSyn = (data) => {
  postFileBatchStopSyn({
    batchName: data.batchName,
  }).then(() => {
    ElMessage.success('结束工商同步成功')
    customTableRef.value.fetchData()
  })
}

const handleFileBatchStopSynBlack = (data) => {
  postFileBatchStopSynBlack({
    batchName: data.batchName,
  }).then(() => {
    ElMessage.success('结束风险等级同步成功')
    customTableRef.value.fetchData()
  })
}

provide('state', state)
</script>
<style scoped>
::v-deep(.upload-file-uploader) {
  margin-bottom: 0;
  margin-right: 6px;
}

::v-deep(.el-upload-list--text) {
  display: none;
}
</style>
